<template>
  <div>
    <!-- 分配权限的弹层 -->
    <el-tree
      ref="tree"
      :data="list"
      :props="{label: 'name'}"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permisson'
import { assignPrem, getRoleDetail } from '@/api/setting'
import { tranListToTreeList } from '@/utils'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 取消
    cancel() {
      // 子传父关闭弹层
      this.$emit('close')
    },
    // 确定
    async hSubmit() {
      try {
        const permIds = this.$refs.tree.getCheckedKeys()
        const res = await assignPrem({ id: this.roleId, permIds: permIds })
        console.log(res, 'assignPrem')
        // 子传父关闭弹层
        this.$emit('close')
      } catch (error) {
        console.log(error)
      }
    },
    async loadPermissionList() {
      try {
        // 获取权限点列表
        const res = await getPermissionList()
        // console.log(res, 'getPermissionList')
        // 获取角色详情
        const perIds = await getRoleDetail(this.roleId)
        // console.log(perIds, 'getRoleDetail')
        // 使用setCheckedKeys选中颜色拥有的权限点
        this.$refs.tree.setCheckedKeys(perIds.data.permIds)
        // 保存数据
        this.list = tranListToTreeList(res.data)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
